<template>
  <div class="container">
    <el-row class="menu-container" :style="{ height: backgroundHeight + 'px' }">
      <el-col :span="24" class="scrollable-menu">
        <h2 class="menu-title">希望信工提供的服务</h2>
        <el-menu
          class="custom-menu"
          background-color="#ffffff"
          text-color="#333"
          active-text-color="#409EFF"
        >
          <!-- 报备管理 -->
          <el-sub-menu index="1">
            <template #title>
              <el-icon><location /></el-icon>
              <span>报备管理</span>
            </template>
            <el-menu-item-group title="报备类型">
              <el-menu-item
                v-for="(item, key) in reportInfo"
                :key="key"
                :index="`1-${key}`"
                @click="emitViewChange('ReportFormTable', { tableType: key })"
              >
                {{ item.model_name }}
              </el-menu-item>
            </el-menu-item-group>
            <el-menu-item-group title="报备统计">
              <el-menu-item
                index="1-2-3"
                @click="emitViewChange('ScoreStatisticsDownload')"
              >
                评分查询
              </el-menu-item>
            </el-menu-item-group>
          </el-sub-menu>


          <!-- 教务管理 -->
          <el-sub-menu index="2">
            <template #title>
              <el-icon><EditPen /></el-icon>
              <span>教务管理</span>
            </template>
            <el-menu-item-group title="教务查询">
              <el-menu-item index="2-1-1">我的课表</el-menu-item>
              <el-menu-item
                index="2-1-2"
                @click="emitViewChange('OwnSchedule')"
              >
                教师课表
              </el-menu-item>
            </el-menu-item-group>
            <el-menu-item-group title="我要调课">
              <el-menu-item
                index="2-2-1"
                @click="emitViewChange('CourseAdjustmentTable')"
              >
                调课申请
              </el-menu-item>
              <el-menu-item
                index="2-2-2"
                @click="emitViewChange('EmptyClassroomQuery')"
              >
                空教室查询
              </el-menu-item>
            </el-menu-item-group>
          </el-sub-menu>

          <!-- 管理模式 -->
          <el-sub-menu v-if="shouldShowMenuItem" index="4">
            <template #title>
              <el-icon><Setting /></el-icon>
              <span>管理模式</span>
            </template>
            <el-sub-menu index="4-1">
              <template #title>
                <el-icon><Setting /></el-icon>
                <span>审核与报备管理</span>
              </template>
              <el-menu-item-group title="报备管理">
                <el-menu-item
                  v-for="(item, key) in reportInfo"
                  :key="key"
                  :index="`4-1-${key}`"
                  @click="emitViewChange('ReportFormTableAdmin', { tableType: key })"
                >
                  {{ item.model_name }}
                </el-menu-item>
              </el-menu-item-group>
              <el-menu-item-group title="评分管理">
                <el-menu-item
                  index="4-1-2"
                  @click="emitViewChange('ScoreStatisticsDownload')"
                >
                  评分导出
                </el-menu-item>
              </el-menu-item-group>
            </el-sub-menu>
            <el-sub-menu index="4-2">
              <template #title>
                <el-icon><Setting /></el-icon>
                <span>选课管理</span>
              </template>
              <el-menu-item index="4-2-1" @click="triggerFileInput">
                选课录入
                <input
                  type="file"
                  style="display: none;"
                  ref="fileInput"
                  @change="handleFileChange"
                />
              </el-menu-item>
              <el-menu-item
                index="4-2-2"
                @click="downloadCourseResult"
              >
                选课结果下载
              </el-menu-item>
              <el-menu-item
                index="4-2-3"
                @click="downloadCourseTemplate"
              >
                选课模板下载
              </el-menu-item>
            </el-sub-menu>
            <el-sub-menu index="4-3">
              <template #title>
                <el-icon><Setting /></el-icon>
                <span>课程管理</span>
              </template>
              <el-menu-item-group title="表管理">
                <el-menu-item
                  index="4-3-1"
                  @click="emitViewChange('CourseAdjustmentTableAdmin')"
                >
                  调课表管理
                </el-menu-item>
                <el-menu-item
                  index="4-3-2"
                  @click="emitViewChange('CourseManagementAdmin')"
                >
                  课程表管理
                </el-menu-item>
              </el-menu-item-group>
            </el-sub-menu>
            <el-sub-menu index="4-4">
              <template #title>
                <el-icon><Setting /></el-icon>
                <span>新报备管理</span>
              </template>
              <el-menu-item @click="emitViewChange('NewReportFiledTableAdmin')">
                <el-icon><Connection /></el-icon>
                <span>报备字段</span>
              </el-menu-item>
              <el-menu-item @click="emitViewChange('ReportItemAdmin')">
                <el-icon><Connection /></el-icon>
                <span>报备审核</span>
              </el-menu-item>
            </el-sub-menu>
          </el-sub-menu>

          <!-- 其他功能 -->
          <el-menu-item
            index="7"
            @click="openGptWeb"
          >
            <el-icon><Connection /></el-icon>
            <span>教案生成器</span>
          </el-menu-item>
          <el-menu-item
            index="8"
            @click="openAssistant"
          >
            <el-icon><Connection /></el-icon>
            <span>智能助理</span>
          </el-menu-item>
<!--          测试功能-->
          <el-menu-item
            index="9"
            @click="emitViewChange('ReportItemPublic')"
          >
            <el-icon><Connection /></el-icon>
            <span>新版报备(测试)</span>
          </el-menu-item>
          <el-menu-item
            index="10"
            @click="emitViewChange('NewReportFiledTable')"
          >
            <el-icon><Connection /></el-icon>
            <span>报备内容(测试)</span>
          </el-menu-item>

        </el-menu>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { Location, Setting, EditPen, Connection } from '@element-plus/icons-vue'
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import setting from "@/setting.js"
import { jsonApi } from "@/global.js"

// 高度定义
const backgroundHeight = ref(720)
const fileInput = ref(null)

// 初始化报告信息
const reportInfo = ref([])
//const userGroups = localStorage.getItem('user_groups')

const handleClose = (key, keyPath) => {
  console.log(key, keyPath)
}

const onMenuItemClick = async (property) => {
  eventBus.emit('report-form-table', {
    tableType: property, // 传递报备类型或其他需要的属性
  })
}
const onMenuItem_2_1_2_Click= async () => {
  eventBus.emit('own-schedule', {})
}
const onMenuItem_2_2_1_Click= async () => {
 eventBus.emit('course-adjustment-form-table', {
  })
}
const onMenuItem_2_2_2_Click= async () => {
  eventBus.emit('empty-classroom-query', {
  })
}
const onMenuItem_2_2_5_Click= async () => {
  eventBus.emit('course-selection-form-table', {
  })
}
const onMenuItem4Click = async () => {
  //跳转
  window.open('https://nextcloud.swjtuhc.top:1443/', '_blank');
}

//管理模式
const onMenuItemApproveClick = async (property) => {
  //跳转到管理界面 setting.APT_URL + 'admins'
  eventBus.emit('report-form-table-admins', {
    tableType: property, // 传递报备类型或其他需要的属性
  })
}

const onMenuItem_4_3_2_1_Click = async () => {
  eventBus.emit('course-adjustment-form-table-admins', {

  })
}
const onMenuItem_4_3_2_2_Click = async () => {
  eventBus.emit('course-management-admins', {
  })
}





const onMenuItemfiyfishwebClick = async () => {
  //跳转到flyfish界面 setting.APT_URL + 'admins'
  window.open('https://fiyfishweb.swjtuhc.top:1443/', '_blank');

}
//获取所有用户的当前的分数
const onMenuItemGetScoreClick = async () => {
  emit('open-score-statistics-table')
}
//获取所有用户的当前的分数
const onMenuItemSocreFileClick = async () => {
  emit('open-score-statistics-table')
}
//选课录入文件上传
//const fileInput=ref(null);
const onMenuItemUploadCourseClick= async () => {
  //弹出上传文件，用data-form上传参数名excel_file
  fileInput.value.click();

}
const handleFileChange = async (event) => {
  // 现在您可以安全地使用file了
  const file = event.target.files[0];
  if (file) {
    //检查file是不是pdf或者zip
    if (file.type === 'application/xlsx') {
      // 显示上传进度
      // 在这里处理文件上传逻辑
      const formData = new FormData();
      formData.append('excel_file', file);
      try {
        const response = await fetch(setting.API_URL + 'courseselection/batchadd/', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`,
          },
          body: formData
        });
        const data = await response.json();
        if (response.ok) {
          ElMessage({
            message: '上传成功',
            type: 'success',
            duration: 2000
          });
        }
      } catch (error) {
        ElMessage({
          message: '上传失败',
          type: 'error',
          duration: 2000
        });
      }
    }else {
      ElMessage({
        message: '请xlsx文件',
        type: 'warning',
        duration: 2000
      });
    }
  }
};


const onMenuItemDownloadCourseResultClick= async () => {
  /*/courseselection/download/*/
  try {
    // 使用fetch API发起请求，以获取Excel文件

    const response = await jsonApi('/courseselection/download/');

    // 检查HTTP响应状态
    if (!response.ok) {
      const errorMessage = await response.text();
      throw new Error(`HTTP error: ${response.status} - ${errorMessage}`);
    }else {
      // 创建一个blob对象，它表示了一段不可变的原始数据
      const blob = await response.blob();

      // 创建一个链接元素，用于下载文件
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;

      // 设置下载的文件名，确保服务器在响应头中设置了正确的文件名
      let fileName = 'downloaded.xlsx'; // 默认文件名
      const contentDisposition = response.headers.get('content-disposition');
      if (contentDisposition) {
        const fileNameMatch = contentDisposition.match(/filename="?([^"]*)"?$/);
        if (fileNameMatch) {
          fileName = fileNameMatch[1]; // 使用从响应头中提取的文件名
        }
      }

      a.download = fileName;

      // 触发下载
      document.body.appendChild(a);
      a.click();

      // 清理资源
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      ElMessage({
        message: '下载成功',
        type: 'success',
        duration: 2000
      });
    }
  }catch (error) {
    ElMessage({
      message: '下载失败',
      type: 'error',
      duration: 2000
    });
    }
}
const onMenuItemDownloadCourseTemplateClick= async () => {
    //打开链接http://xgsys.swjtuhc.top:1080/Files/FileTemplate/选课模板.xlsx
  window.open('https://xgsys.swjtuhc.top:1443/Files/FileTemplate/选课模板.xlsx', '_blank');
}
const userGroups = localStorage.getItem('user_groups');
const shouldShowMenuItem = computed(() => {
  return userGroups.includes('reviewer') || userGroups.includes('TDAdmin')
})

// 组件挂载
onMounted(() => {
  const storedReportInfo = localStorage.getItem('reportinfo')
  if (storedReportInfo) {
    reportInfo.value = JSON.parse(storedReportInfo)
  }
  backgroundHeight.value = window.innerHeight
})

// 统一视图切换事件
const emit = defineEmits(['view-change'])

const emitViewChange = (view, props = {}) => {
  emit('view-change', { view, ...props })
}

// 文件操作相关方法
const triggerFileInput = () => {
  fileInput.value?.click()
}

/*const handleFileChange = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  if (file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
    const formData = new FormData()
    formData.append('excel_file', file)

    try {
      const response = await fetch(setting.API_URL + 'courseselection/batchadd/', {
        method: 'POST',
        headers: { 'Authorization': `Bearer ${localStorage.getItem('access_token')}` },
        body: formData
      })

      if (response.ok) {
        ElMessage.success('上传成功')
      } else {
        throw new Error('上传失败')
      }
    } catch (error) {
      ElMessage.error('上传失败')
    }
  } else {
    ElMessage.warning('请上传xlsx文件')
  }
}*/

const downloadCourseResult = async () => {
  try {
    const response = await jsonApi('/courseselection/download/')

    if (response.ok) {
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = '选课结果.xlsx'
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      window.URL.revokeObjectURL(url)
      ElMessage.success('下载成功')
    } else {
      throw new Error('下载失败')
    }
  } catch (error) {
    ElMessage.error('下载失败')
  }
}

const downloadCourseTemplate = () => {
  window.open('https://xgsys.swjtuhc.top:1443/Files/FileTemplate/选课模板.xlsx', '_blank')
}

// 外部链接功能
const openGptWeb = () => {
  emitViewChange('WebIframe', { webUrl: 'https://aitools.swjtuhc.top:12443' })
}

const openAssistant = () => {
  const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
  const url = isMobile
    ? 'https://wx.baeapps.com/api/ai_apaas/v1/wx_program/share?share_code=appULYNtvGp5cOvL09EemFG'
    : 'https://appbuilder.baidu.com/s/ZtxSfpXn'

  if (isMobile) {
    emitViewChange('WebIframe', { webUrl: url })
  } else {
    window.open(url, '_blank')
  }
}
</script>

<style scoped>
/* 保持原有样式不变 */
.container {
  padding: 20px;
  background: #f5f7fa;
  height: 100vh;
}

.menu-container {
  height: 100%;
  overflow-y: auto;
}

.scrollable-menu {
  padding: 0 20px;
}

.menu-title {
  margin: 10px 0;
  font-size: 18px;
  color: #333;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.custom-menu {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 10px;
}

.custom-menu .el-menu-item,
.custom-menu .el-sub-menu__title {
  height: 48px;
  line-height: 48px;
  padding: 0 20px;
  border-radius: 4px;
  transition: all 0.3s;
}

.custom-menu .el-menu-item:hover,
.custom-menu .el-sub-menu__title:hover {
  background-color: #f5f7fa;
}

.custom-menu .el-menu-item.is-active {
  background-color: #e6f7ff !important;
  color: #409EFF !important;
}

@media (max-width: 768px) {
  .menu-title {
    font-size: 16px;
  }

  .custom-menu .el-menu-item,
  .custom-menu .el-sub-menu__title {
    height: 44px;
    line-height: 44px;
  }
}
</style>